package com.wxq.day0419.validator;

import com.wxq.day0419.pojo.Goods;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.Date;

@Component
public class GoodsValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        //验证的class如果不是Goods.class 则不验证
        return true;
    }

    /**
     * 1.商品名称和商品详情不能为空
     * 2.商品价格在0-100之间
     * 3.创建日期不能在系统日期后
     *
     * @param target
     * @param errors
     */
    @Override
    public void validate(Object target, Errors errors) {
        Goods goods = (Goods) target;
        //添加商品名称非空验证规则
        ValidationUtils.rejectIfEmpty(errors, "gname", "goods.name.required");
        //添加商品详情非空验证规则
        ValidationUtils.rejectIfEmpty(errors, "gdescription", "goods.gdescription.required");
        //商品价格在0-100之间
        if (goods.getGprice() <= 0 || goods.getGprice() > 100) {
            errors.rejectValue("gprice", "goods.gprice.invalid");
        }
        //创建日期不能在系统日期后
        Date goodsDate = goods.getGdate();
        if (goodsDate != null && goodsDate.after(new Date())) {
            errors.rejectValue("gdate", "goods.gdate.invalid");
        }
    }
}